package nodes

import (
	"encoding/json"
	"gitee.com/theegg/go-brick/app/model"
	"gitee.com/theegg/go-brick/app/model/content/tags"
	"gitee.com/theegg/go-brick/app/service/app"
	"gitee.com/theegg/go-brick/app/service/help/credis"
	"github.com/go-redis/redis/v8"
	"strconv"
)

var CacheKeyPrefix = TableName + "_"

// 获取单个数据 detail 所有加工过的数据
// @param id int64 数据的id
// @return *Nodes
func GetItemDetailCacheById(id int64) (map[string]interface{}, error) {
	key := CacheKeyPrefix + "detail" + "_" + strconv.FormatInt(id, 10)
	redisOp := credis.New()
	data, errGet := redisOp.Get(key)
	if errGet != nil {
		if errGet == redis.Nil {
			nodeItem, errDb := GetItemById(id)
			if errDb != nil {
				return nil, app.NewError(errDb)
			}

			// 获取tag
			tagDbData, errTag := tags.GetTagsByNodeId(nodeItem.Id)
			if errTag != nil {
				return nil, errTag
			}

			tagData := make([]string, 0)
			for _, v := range tagDbData {
				tagData = append(tagData, v.TagTitle)
			}

			detail := map[string]interface{}{
				"id":              nodeItem.Id,
				"title":           nodeItem.Title,
				"category_id":     nodeItem.CategoryId,
				"username":        nodeItem.AuthorName,
				"content":         nodeItem.Content,
				"summary":         nodeItem.Summary,
				"image_cover":     nodeItem.ImageCover,
				"image_cover_url": app.GetImageStaticUrl(nodeItem.ImageCover),
				"comment_state":   nodeItem.CommentState,
				"public_time":     nodeItem.UpdatedAt.Format("2006-01-02 15:04:05"),
				"tags":            tagData,
			}

			jsonData, _ := json.Marshal(detail)

			errSet := redisOp.Set(key, string(jsonData), 0)
			if errSet != nil {
				panic(errGet)
			}

			return detail, nil
		}
		panic("Redis-node-cache-detail-" + errGet.Error())
	}

	var returnData map[string]interface{}
	jsonErr := json.Unmarshal(data, &returnData)
	if jsonErr != nil {
		return nil, app.NewError(jsonErr)
	}

	return returnData, nil
}

// @title DeleteDetailCacheById
// @description 刷新指定的id的detail缓存
func DeleteDetailCacheById(id int64) (bool, error) {
	key := CacheKeyPrefix + "detail" + "_" + strconv.FormatInt(id, 10)
	redisOp := credis.New()
	_, err := redisOp.Del(key)
	if err != nil {
		return false, err
	}

	return true, nil
}

// 获取单个数据
// @param id int64 数据的id
// @return *Nodes
func GetItemFromCacheById(id int64) (*Nodes, error) {
	key := CacheKeyPrefix + strconv.FormatInt(id, 10)
	redisOp := credis.New().Tag(TableName)
	data, errGet := redisOp.TGet(key)
	if errGet != nil {
		if errGet == redis.Nil {
			data, errDb := GetItemById(id)
			if errDb != nil {
				return nil, app.NewError(errDb)
			}

			jsonData, _ := json.Marshal(data)

			_, errSet := redisOp.TSet(key, jsonData)
			if errSet != nil {
				panic(errGet)
			}

			return data, nil
		}
		panic("Redis-node-cache-" + errGet.Error())
	}

	var returnData *Nodes
	jsonErr := json.Unmarshal(data, &returnData)
	if jsonErr != nil {
		return nil, app.NewError(jsonErr)
	}

	return returnData, nil
}

// @title DeleteById
// @description 刷新指定的id
func DeleteCacheById(dc model.DbContext, id int64) (bool, error) {
	redisOp := dc.GetRedisConn().Tag(TableName)
	key := CacheKeyPrefix + strconv.FormatInt(id, 10)
	_, err := redisOp.TDel(redisOp.GetTag(), key)
	if err != nil {
		return false, err
	}

	return true, nil
}

// @title FlushTag
// @description 删除tag上所有的
func FlushCacheByTag(dc model.DbContext) {
	redisOp := dc.GetRedisConn().Tag(TableName)
	redisOp.FlushTag()
}
